import { Component, OnInit } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { CartService } from '../../../service/cart/cart.service';
import { NzMessageService, NzModalService, NzNotificationService, UploadFile } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { CommService } from '../../../service/comm/comm.service';

@Component({
  selector: 'order-cart-list',
  templateUrl: './cart-list.component.html',
  styleUrls: ['./cart-list.component.less']
})
export class OrderCartListComponent implements OnInit {
  nodata = true;
  private list: Array<any>;
  private total: number = 0;
  private totalPrice: number = 0;
  loading = false;
  imgSuffix = '';
  defaultUrl = './assets/tmp/img/dummy.png';
  currency = null;
  constructor(
    private cartServ: CartService,
    private msg: NzMessageService,
    private comm: CommService,
    private modalService: NzModalService,
    private setting: SettingsService,
    private notice: NzNotificationService,
  ) { }

  ngOnInit() {
    this.init();
  }
  _onReuseInit() {
    this.init();
  }

  init() {
    this.currency = this.setting.user.currency;
    this.imgSuffix = this.comm.getGoodsUrl();
    this.list = [];
    this.load();
  }


  load() {
    this.loading = true;
    this.cartServ.list().pipe(catchError(err => {
      return of(err)
    })).subscribe(res => {
        this.loading = false;
        if (res.status === 200) {
            this.list = [res.data];
            this.total = this.orderCount();
            this.calcTotalPrice();
            this.checkNoData();
        }
    });
  }

  /**
   * 计算所有明细数量
   */
  orderCount() {
    let count = 0;
    for (let i = 0; i < this.list.length; i++) {
        for (let cart of this.list[i].detail) {
            count += +cart.qty;
        }
    }
    return count;
  }

  calcTotalPrice() {
    this.totalPrice = 0;
    for (let order of this.list) {
        for (let cart of order.detail) {
            this.totalPrice += (cart.qty * cart.price);
        }
    }
  }

  checkNoData() {
    let num = this.orderCount();
    if (num > 0) {
        this.nodata = false;
    } else {
        this.nodata = true;
    }
  }

  /**
   * 根据订单，计算明细总数,并返回
   * @param o
   */
  calcOrderQty(o):number {
      o.qty = 0;
      o.price = 0;
      // 重新计算总数
      for (let i = 0; i < o.detail.length; i++) {
          o.qty += +o.detail[i].qty;
          o.price += (o.detail[i].qty * o.detail[i].price);
      }
      return o.qty;
  }

  qtyChange(detail, order, val) {
    this.cartServ.modifyCart(detail.productCd, val).pipe(
      catchError(err => {
        return of(err)
      })
    ).subscribe(res => {
      if (res.status === 200) {
          this.calcOrderQty(order);
          this.calcTotalPrice();
          this.total = this.orderCount();
      } else {
        this.msg.error(res.message);
      }
    })
  }

  removeHead() {
    this.showDeleteConfirm("The cart will be deleted!", () => {
      this.loading = true;
      this.cartServ.delByBrand().pipe(
        catchError(err => { return of(err) })
      ).subscribe(data => {
        this.loading = false;
        if (data.status === 200) {
          this.msg.success('The cart has been deleted');
          // 删除明细
          this.list = [];
          // 重新计算该订单的明细数
          this.total = this.orderCount();
          // 重新计算总金额
          this.calcTotalPrice();
          this.checkNoData();
        } else {
          this.msg.error(data.message);
        }
      })
    }, () => {});
  }

  showDeleteConfirm(content, okFunc, cancelFunc): void {
    this.modalService.confirm({
      nzTitle     : 'Are you sure?',
      nzContent   : '<b style="color: red;">' + content +'</b>',
      nzOkText    : 'Yes',
      nzOkType    : 'danger',
      nzOnOk      : okFunc,
      nzCancelText: 'No',
      nzOnCancel  : cancelFunc
    });
  }

  /**
   * 删除购物车明细
   * @param detail
   * @param order
   */
  remove(detail, order) {
    this.showDeleteConfirm("The item will be deleted!", () => {
      this.loading = true;
      this.cartServ.delBySku(detail.productCd).pipe(
        catchError(err => { return of(err) })
      ).subscribe(data => {
        this.loading = false;
        if (data.status === 200) {
          this.msg.success('The item has been deleted');
          let arr = order.detail.slice();
          // 删除明细
          arr.splice(arr.findIndex(obj => obj.productCd === detail.productCd), 1);
          order.detail = arr;
          // 重新计算该订单的明细数
          this.calcOrderQty(order);
          this.total = this.orderCount();
          // 重新计算总金额
          this.calcTotalPrice();
          this.checkNoData();
        } else {
          this.msg.error(data.message);
        }
      })
    }, () => {});
  }

  sumbitCart() {
    this.modalService.confirm({
      nzTitle     : 'Are you sure?',
      nzContent   : '<b style="color: red;">The order will be submit</b>',
      nzOkText    : 'Yes',
      nzOkType    : 'warning',
      nzOnOk      : () => {
        this.loading = true;
        this.cartServ.creatOrder().pipe(catchError(err => {
          return of(err)
        })).subscribe(data => {
          this.loading = false;
          if (data.status === 200) {
            this.msg.success('success');
            // 删除明细
            this.list = [];
            // 重新计算该订单的明细数
            this.total = this.orderCount();
            // 重新计算总金额
            this.calcTotalPrice();
            this.checkNoData();
          } else {
            this.msg.error(data.message);
          }
        });
      },
      nzCancelText: 'No',
      nzOnCancel  : () => {}
    });
  }

  data = [];
  importExcelUrl = this.cartServ.uploadCart();

  batchImport(info: { file: UploadFile }) {

    if (info.file.status === 'uploading') {
      this.loading = true;
    }
    if (info.file.status === 'done') {
      this.loading = false;
      this.notice.create('success', 'Success', info.file.response.data['successTip']);
      if (undefined !== info.file.response.data['failTip']) {
        this.notice.create('info', 'Info', info.file.response.data['failTip']);
      }
      this.init();
    }
    if (info.file.status === 'error') {
      this.loading = false;
      this.notice.create('error', 'Error', info.file.response.msg);
    }
  }
}
